<script setup>
import { useUserStore } from "@/stores"; // 引入用户信息相关的store模块
import { ref, watch, onMounted } from "vue"; // 引入Vue的ref函数用于创建响应式变量
import {
  userUpdateInfoService,
  userUpdatePassService,
  userMgrUpdateService,
  userGetAvatarListService,
  uploadService,
} from "@/api"; // 引入用于更新用户信息的API服务
import { Edit, MagicStick, User, Lock } from "@element-plus/icons-vue";
import { formatTime } from "@/utils/format";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import UserAvatar from "./components/UserAvatar.vue";

// 从useUserStore中解构出用户基本信息和获取用户信息的函数
const {
  user: { name, description, username, id },
  getUserInfo,
} = useUserStore();
const userInfoStore = useUserStore();

// 创建一个包含用户信息的响应式变量，初始值为从store中获取的用户信息
const userInfo = ref({ name, description, username, id });

// 定义表单校验规则
const rules = {
  name: [
    { required: true, message: "请输入用户昵称", trigger: "blur" },
    {
      pattern: /^\S{2,10}$/,
      message: "昵称必须是2-10位的非空字符串",
      trigger: "blur",
    },
  ],
  description: [{ required: true, message: "请输入用户描述", trigger: "blur" }],
};

// 创建一个对Vue表单组件的引用
const formRef = ref();

// 初始化一个名为loading的ref，用于追踪加载状态
let loading = ref(false);

/**
 * 提交表单时的处理函数。
 * 首先验证表单数据的有效性，如果有效则调用API更新用户信息，
 * 更新成功后刷新用户信息并显示成功消息。
 */
const onSubmit = async () => {
  loading.value = true;
  try {
    const valid = await formRef.value.validate(); // 验证表单数据
    if (valid) {
      await userMgrUpdateService(userInfo.value); // 调用更新用户信息的API
      await getUserInfo(); // 刷新用户信息
      ElMessage.success("修改成功"); // 显示成功消息
    }
  } catch (error) {
    ElMessage.error("修改失败"); // 显示成功消息
  } finally {
    loading.value = false;
  }
};

let circleUrl = ref(
  "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
);

// 重置密码模块--------------------start
// 定义密码表单的初始状态
const pwdForm = ref({
  newPassword: "",
  truePassword: "",
  againPassword: "",
});

/**
 * 验证新密码和旧密码不能相同
 * @param {Object} rule 验证规则对象
 * @param {string} value 新密码的值
 * @param {Function} cb 回调函数，验证通过或不通过时调用
 */
const checkOldSame = (rule, value, cb) => {
  if (value === pwdForm.value.truePassword) {
    cb(new Error("原密码和新密码不能一样!"));
  } else {
    cb();
  }
};

/**
 * 验证新密码和确认密码是否相同
 * @param {Object} rule 验证规则对象
 * @param {string} value 确认密码的值
 * @param {Function} cb 回调函数，验证通过或不通过时调用
 */
const checkNewSame = (rule, value, cb) => {
  if (value !== pwdForm.value.newPassword) {
    cb(new Error("新密码和确认再次输入的新密码不一样!"));
  } else {
    cb();
  }
};

// 定义表单的验证规则
const pwdRules = {
  // 原密码规则
  truePassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码长度必须是6-15位的非空字符串",
      trigger: "blur",
    },
  ],
  // 新密码规则
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码长度必须是6-15位的非空字符串",
      trigger: "blur",
    },
    { validator: checkOldSame, trigger: "blur" },
  ],
  // 确认新密码规则
  againPassword: [
    { required: true, message: "请再次确认新密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码长度必须是6-15位的非空字符串",
      trigger: "blur",
    },
    { validator: checkNewSame, trigger: "blur" },
  ],
};

// 获取表单引用
const formPwdRef = ref();
// 获取路由实例
const router = useRouter();
// 获取用户状态管理实例
const userStore = useUserStore();
// 定义加载状态
let loadingPwd = ref(false);

/**
 * 提交表单，更新密码
 */
const onSubmitPwd = async () => {
  loadingPwd.value = true;
  // 验证表单
  try {
    const valid = await formPwdRef.value.validate();
    if (valid) {
      // 调用更新密码服务
      await userUpdatePassService(pwdForm.value);
      // 成功提示，清除用户信息并跳转到登录页
      ElMessage({ type: "success", message: "更换密码成功" });
      userStore.setToken("");
      userStore.setUserInfo({});
      router.push("/login");
    }
  } catch (error) {
    ElMessage.error("修改失败");
  } finally {
    loadingPwd.value = false;
  }
};

// 重置表单
const onReset = () => {
  formPwdRef.value.resetFields();
};
// 重置密码模块-----------------end

// 切换到菜单栏
let activeName = ref("1");
let route = useRoute();

const editAvatar = (active = "1") => {
  console.log(active);
  activeName.value = active;
  if (route.query.active) {
    activeName.value = route.query.active;
  }
};
editAvatar();
// 监听 route.query.active 的变化
watch(
  () => route.query.active,
  (newValue) => {
    editAvatar(newValue);
  }
);
</script>

<template>
  <page-container title="基本资料">
    <el-row :gutter="20">
      <el-col :span="3" style="min-width: 180px">
        <div class="col avatarContent">
          <el-avatar
            :size="130"
            :src="userInfoStore.user.head_url"
            class="avatar"
            @click="editAvatar('3')"
          />

          <div class="edit" @click="editAvatar('3')">
            <el-icon color="#3070FF"><Edit /></el-icon>
          </div>
        </div>
      </el-col>
      <el-col :span="5" style="min-width: 280px"
        ><div class="col info">
          <div class="list">
            <div class="title">昵称：</div>
            <div class="description" style="color: #50a6ff">
              {{ userInfoStore.user.name }}
            </div>
          </div>
          <div class="list">
            <div class="title">用户名：</div>
            <div class="description">{{ userInfoStore.user.username }}</div>
          </div>
          <div class="list">
            <div class="title">注册时间：</div>
            <div class="description">
              {{ formatTime(userInfoStore.user.create_time) }}
            </div>
          </div>
        </div></el-col
      >
      <el-col :span="5" style="min-width: 280px"
        ><div class="col info">
          <div class="list">
            <div class="title" style="margin-left: -30px">身份：</div>
            <div class="description">
              {{ userInfoStore.user.description
              }}<el-tag type="success">已认证</el-tag>
            </div>
          </div>
          <div class="list" style="margin-left: -30px">
            <div class="title">描述：</div>
            <div class="description">{{ userInfoStore.user.description }}</div>
          </div>
          <div class="list">
            <div class="title"></div>
            <div class="description">&#8203;</div>
          </div>
        </div></el-col
      >
    </el-row>
    <el-row class="tabContainer">
      <el-tabs
        type="border-card"
        style="width: 100%"
        class="demo-tabs"
        v-model="activeName"
      >
        <el-tab-pane name="1">
          <template #label>
            <span class="custom-tabs-label">
              <el-icon><user /></el-icon>
              <span> 修改信息</span>
            </span>
          </template>
          <el-row>
            <el-col :span="8">
              <el-form
                :model="userInfo"
                :rules="rules"
                ref="formRef"
                label-width="100px"
                size="large"
              >
                <el-form-item label="用户名">
                  <el-input v-model="userInfo.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="name">
                  <el-input v-model="userInfo.name"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                  <el-input v-model="userInfo.description"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="onSubmit" :loading="loading"
                    >提交</el-button
                  >
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="重置密码" name="2">
          <template #label>
            <span class="custom-tabs-label">
              <el-icon><Lock /></el-icon>
              <span> 重置密码</span>
            </span>
          </template>
          <el-row>
            <el-col :span="8">
              <el-form
                :model="pwdForm"
                :rules="pwdRules"
                ref="formPwdRef"
                label-width="100px"
                size="large"
              >
                <el-form-item label="原密码" prop="truePassword">
                  <el-input
                    v-model="pwdForm.truePassword"
                    type="password"
                  ></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="pwdForm.newPassword"
                    type="password"
                  ></el-input>
                </el-form-item>
                <el-form-item label="确认新密码" prop="againPassword">
                  <el-input
                    v-model="pwdForm.againPassword"
                    type="password"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                    @click="onSubmitPwd"
                    type="primary"
                    :loading="loadingPwd"
                    >修改密码</el-button
                  >
                  <el-button @click="onReset">重置</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="生成头像" name="3">
          <template #label>
            <span class="custom-tabs-label">
              <el-icon><magicStick /></el-icon>
              <span> 生成头像</span>
            </span>
          </template>
          <UserAvatar></UserAvatar>
        </el-tab-pane>
      </el-tabs>
    </el-row>
  </page-container>
</template>
<style lang="scss" scoped>
.col {
  height: 160px;
  background-color: #f5f7fa;
  margin-bottom: 20px;
}
.avatarContent {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  .edit {
    width: 30px;
    height: 30px;
    background: #e8f4ff;
    position: absolute;
    bottom: 20px;
    right: 15px;
    z-index: 1;
    border-radius: 50%;
    border: 2px solid #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
  .avatar {
    border: 1px solid #eee;
    transition: 0.2s;
  }
  &:hover .avatar {
    border-color: #409eff;
    cursor: pointer;
  }
}
.info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  .list {
    display: flex;
    margin: 5px 0;
    .title {
      width: 100px;
      text-align: right;
      margin-right: 15px;
    }
  }
}
.tabContainer {
  background-color: #f5f7fa;
  min-height: 600px;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.demo-tabs .custom-tabs-label .el-icon {
  vertical-align: middle;
}
.demo-tabs .custom-tabs-label span {
  vertical-align: middle;
  margin-left: 4px;
}
</style>
